<template>
  <div class="app-container">
    <div style="padding: 10px 0;">
      <PayFormFilter
        @on-filter="submitFilterForm"
      />
    </div>
    <div class="button-group">
      <el-button
        v-if="roleCheck(paySetType.withdrawAdd)"
        type="primary"
        :loading="loading"
        @click="openDialog({dialogName: dialogType.addPay, props: {}})"
      >
        新增三方平台
      </el-button>
      <el-button
        v-if="roleCheck(paySetType.withdrawStatus)"
        type="primary"
        :disabled="!isChecked"
        :loading="loading"
        @click="openDialog({
          dialogName: dialogType.confirmStatus,
          props: {
            contentProps: constType.openAll,
            cacheData: { row: null, status : constType.statusOpen }
          },
        })"
      >
        批量开启商户
      </el-button>
      <el-button
        v-if="roleCheck(paySetType.withdrawStatus)"
        type="primary"
        :disabled="!isChecked"
        :loading="loading"
        @click="openDialog({
          dialogName: dialogType.confirmStatus,
          props: {
            contentProps: constType.closeAll,
            cacheData: { row: null, status : constType.statusClose }
          },
        })"
      >
        批量关闭商户
      </el-button>
    </div>
    <el-table
      border
      :data="tableData.list"
      v-loading="loading"
      element-loading-text="加载中..."
      class="el-table-align-center"
      @selection-change="onChangeSelection"
    >
      <el-table-column
        type="selection"
        width="55"
      >
      </el-table-column>
      <el-table-column label="三方平台" prop="channelName" width="180" align="center">
        <template slot-scope="{row}">
          {{row.channelName}}
        </template>
      </el-table-column>
      <el-table-column label="商户号" prop="merchantCode" align="center">
        <template slot-scope="{row}">
          <el-tooltip
            placement="top"
            v-if="row.merchantCode && row.merchantCode.length > constType.ellipsisLen + 5"
          >
            <div slot="content" class="global-table-tooltip-item-view">
              {{row.merchantCode}}
            </div>
            <div class="global-table-single-item-view">{{row.merchantCode}}</div>
          </el-tooltip>
          <div class="global-table-single-item-view" v-else>{{row.merchantCode}}</div>
        </template>
      </el-table-column>
      <el-table-column label="公钥" prop="publicKey" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('withdraw-key-show')">
            <el-tooltip
              placement="top"
              v-if="row.publicKey && row.publicKey.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.publicKey}}
              </div>
              <div class="global-table-single-item-view">{{row.publicKey}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.publicKey}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="私钥" prop="privateKey" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('withdraw-key-show')">
            <el-tooltip
              placement="top"
              v-if="row.privateKey && row.privateKey.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.privateKey}}
              </div>
              <div class="global-table-single-item-view">{{row.privateKey}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.privateKey}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="请求URL" prop="payUrl" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('withdraw-url-show')">
            <el-tooltip
              placement="top"
              v-if="row.payUrl && row.payUrl.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.payUrl}}
              </div>
              <div class="global-table-single-item-view">{{row.payUrl}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.payUrl}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="接收URL" prop="notifyUrl" align="center">
        <template slot-scope="{row}">
          <div v-if="roleCheck('withdraw-url-show')">
            <el-tooltip
              placement="top"
              v-if="row.notifyUrl && row.notifyUrl.length > constType.ellipsisLen"
            >
              <div slot="content" class="global-table-tooltip-item-view">
                {{row.notifyUrl}}
              </div>
              <div class="global-table-single-item-view">{{row.notifyUrl}}</div>
            </el-tooltip>
            <div class="global-table-single-item-view" v-else>{{row.notifyUrl}}</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="每日出款上限" prop="dailyLimit" align="center">
        <template slot-scope="{row}">
          {{row.dailyLimit | currency}}
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" prop="lastUpdate" align="center">
        <template slot-scope="{row}">
          {{row.lastUpdate | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="上下架状态" prop="status" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.status, payEnum.ESCROWS_STATUS_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="开启状态" prop="status" align="center">
        <template slot-scope="{row}">
          {{getLabel(row.openStatus, payEnum.PAY_STATUS_TYPE)}}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center">
      </el-table-column>
      <el-table-column label="操作" width="180px" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button
            type="text"
            v-if="row.status === constType.escrowOpen && roleCheck(paySetType.withdrawSwitch)"
            @click="onToggleEscrowStatus(row, constType.escrowClose)"
          >
            下架
          </el-button>
          <el-button
            type="text"
            v-else-if="row.status === constType.escrowClose && roleCheck(paySetType.withdrawSwitch)"
            @click="onToggleEscrowStatus(row, constType.escrowOpen)"
          >
            上架
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.withdrawEdit)"
            type="text"
            @click="openDialog({dialogName: dialogType.addPay, props: row })"
          >
            编辑
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.withdrawDelete)"
            type="text"
            @click="onClickDeleteItem(row)"
          >
            删除
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.withdrawStatus) && row.openStatus === constType.statusOpen"
            type="text"
            @click="openDialog({
              dialogName: dialogType.confirmStatus,
              props: {
                contentProps: constType.closeSingle,
                cacheData: { row, status : constType.statusClose }
              },
            })"
          >
            关闭
          </el-button>
          <el-button
            v-if="roleCheck(paySetType.withdrawStatus) && row.openStatus === constType.statusClose"
            type="text"
            @click="openDialog({
              dialogName: dialogType.confirmStatus,
              props: {
                contentProps: constType.openSingle,
                cacheData: { row, status : constType.statusOpen }
              },
            })"
          >
            开启
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      >
      </el-pagination>
    </div>
    <PayEditDialog
      v-if="dialogName === dialogType.addPay"
      v-model="dialogVisible"
      :row-data="dialogProps"
      @submit="submitFinished"
    />
    <ConfirmStatusDialog
      v-if="dialogName === dialogType.confirmStatus"
      v-model="dialogVisible"
      :rowData="dialogProps"
      @confirm="onToggleStatus"
      footText="注：商户开启后才可以在“出款配置及应用”中应用并上架，若是关闭则“出款配置及应用”中的商户为关闭状态；关闭后财务出款人员无法使用此三方商户出款"
    />
  </div>
</template>


<script>

// constants
import { messageType } from '@/const/enum';
import { constType } from '@/const/payEnum';
import { paySetType } from '@/router/payRoutes';

// components
import PayFormFilter from './payFormFilter';
import PayEditDialog from './payEditDialog';
import ConfirmStatusDialog from './confirmStatusDialog';

// services
import {
  getWithdrawMerchantList,
  updatePaymentWithdrawOpenStatus,
  updatePaymentWithdrawStatus,
  delPaymentWithdraw,
} from '@/services/api/payment';

// mixins
import { grid, constsLabel, dialog } from '@/build';

const dialogType = {
  addPay: 'pay-edit-dialog',
  confirmStatus: 'confirm-status-dialog',
};

export default {
  name: 'pay',
  components: {
    PayFormFilter,
    PayEditDialog,
    ConfirmStatusDialog,
  },
  mixins: [grid, constsLabel, dialog],
  data() {
    return {
      paySetType,
      filters: {
        page: 1,
        size: 20,
      },
      tableData: {},
      tableSelectionList: [],
      dialogType,
      constType,
    };
  },
  computed: {
    isChecked() {
      return Array.isArray(this.tableSelectionList) && !!this.tableSelectionList.length;
    },
  },
  methods: {
    onChangeSelection(val) {
      this.tableSelectionList = val;
    },
    getCurrMerchantId(row) {
      if (row && Object.keys(row).length) {
        return `${row.merchantId}`;
      }
      return this.tableSelectionList.map(item => item.merchantId).join(',');
    },
    async onToggleStatus({ row, status }) {
      try {
        this.loading = true;
        const merchantIds = this.getCurrMerchantId(row);
        const [bool, result] = await updatePaymentWithdrawOpenStatus({
          merchantIds,
          status,
        });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: `${status === constType.statusClose ? '关闭' : '开启'}成功`,
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      } finally {
        this.loading = false;
      }
    },
    async onClickDeleteItem({ merchantId }) {
      try {
        await this.$confirm('确定要删除三方出款商户吗？', '删除三方出款商户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const [bool, result] = await delPaymentWithdraw({ merchantId });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: '删除成功',
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
    async onToggleEscrowStatus({ merchantId }, status) {
      try {
        const display = status === constType.escrowOpen ? '上架' : '下架';
        await this.$confirm(`确定要${display}三方出款商户吗？`, `${display}三方出款商户`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const [bool, result] = await updatePaymentWithdrawStatus({ merchantId, status });
        if (!bool) throw new Error(result.message);
        this.gridSearch();
        this.$notify({
          type: 'success',
          message: `${display}成功`,
        });
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          message: e.message,
          type: 'error',
        });
      }
    },
  },
  mounted() {
    this.bindGet(getWithdrawMerchantList, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.getAll();
  },
};
</script>

<style lang="scss">

</style>
